package com.macro.mall.portal.controller;

import com.macro.mall.common.api.CommonResult;
import com.macro.mall.model.UmsMember;
import com.macro.mall.model.UmsMemberAll;
import com.macro.mall.model.UmsMemberLog;
import com.macro.mall.portal.domain.MemberVO;
import com.macro.mall.portal.service.UmsMemberLogService;
import com.macro.mall.portal.service.UmsMemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;

/**
 * 会员登录注册管理Controller
 * Created by macro on 2018/8/3.
 */
@Slf4j
@RestController
@Api(tags = "UmsMemberController", description = "会员登录注册管理")
@RequestMapping("/sso")
public class UmsMemberController {
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private UmsMemberService memberService;
    @Autowired
    private UmsMemberLogService umsMemberLogService;

    private boolean isDebugEnabled = true;

    @ApiOperation("会员注册")
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult register(@ApiParam(value = "请求报文") @RequestBody MemberVO request) {
        Map<String, Object> register = memberService.register(request);
        return CommonResult.success(register);
    }

    @ResponseBody
    @ApiOperation("会员登录")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public CommonResult login(@ApiParam(value = "请求报文") @RequestBody MemberVO request) {

        Map<String, String> info = memberService.login(request);
        String token = info.get("token");
        if (token == null) {
            return CommonResult.validateFailed("用户名或密码错误");
        }
        return CommonResult.success(info);
    }

    @ApiOperation("获取会员信息")
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult info(Principal principal) {
        if(principal==null){
            return CommonResult.unauthorized(null);
        }
        UmsMember member = memberService.getCurrentMember();
        return CommonResult.success(member);
    }

    @ApiOperation("获取数据库会员信息")
    @RequestMapping(value = "/getInfo", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult getInfoById(Principal principal) {
        if(principal==null){
            return CommonResult.unauthorized(null);
        }
        UmsMember a = memberService.getCurrentMember();
        UmsMember member = memberService.getById(a.getId());
        UmsMemberLog umLog = umsMemberLogService.findOneNewestComplete(member.getId());
        if (!StringUtils.isEmpty(umLog)) {
            member.setCompletePage(umLog.getCompletePage());
            member.setCompletePageStatus(umLog.getStatus());
        } else {
            member.setCompletePage(0);
        }
        if (isDebugEnabled) {
            log.debug("执行获取MbrMember数据集-->结果:", member);
        }
        return CommonResult.success(member);
    }

    @ApiOperation("获取验证码")
    @RequestMapping(value = "/getAuthCode", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult getAuthCode(@RequestParam("telephone") String telephone,@RequestParam("sendType")String sendType) {

        if(telephone.equals("13121374111")){
            return CommonResult.success("获取验证码成功");
        }
        String authCode = memberService.generateAuthCode(telephone,sendType);
        return CommonResult.success(authCode,"获取验证码成功");
    }

    @ApiOperation("修改密码")
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult updatePassword(Principal principal, @ApiParam(value = "请求报文") @RequestBody MemberVO request) {
        if(principal==null){
            return CommonResult.unauthorized(null);
        }
        memberService.updatePassword(request);
        return CommonResult.success(null,"密码修改成功");
    }


    @ApiOperation(value = "刷新token")
    @RequestMapping(value = "/refreshToken", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult refreshToken(HttpServletRequest request) {
        String token = request.getHeader(tokenHeader);
        String refreshToken = memberService.refreshToken(token);
        if (refreshToken == null) {
            return CommonResult.failed("token已经过期！");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", refreshToken);
        tokenMap.put("tokenHead", tokenHead);
        return CommonResult.success(tokenMap);
    }

    @ApiOperation(value = "修改用户信息")
    @RequestMapping(value = "/updateInfo", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult updateInfo(Principal principal, @ApiParam(value = "请求报文") @RequestBody UmsMember request) {
        if(principal==null){
            return CommonResult.unauthorized(null);
        }
        memberService.updateInfo(request);
        return CommonResult.success(null,"信息修改成功");
    }
    @ApiOperation(value = "获取会员信息（包含入住信息与志愿者信息）")
    @RequestMapping(value = "/getMemberAllById", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult getMemberAllById(Long memberId) {
        if(memberId==null){
            return CommonResult.unauthorized(null);
        }
        UmsMemberAll memberAll = memberService.getMemberAllById(memberId);
        return CommonResult.success(memberAll);
    }
    @ApiOperation(value = "保存入住信息与志愿者信息")
    @RequestMapping(value = "/saveMemberCheckIn", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult saveMemberCheckIn(@ApiParam(value = "请求报文") @RequestBody UmsMemberAll memberAll) {
        try {
            memberService.saveMemberCheckIn(memberAll);
            return CommonResult.success(null, "操作成功");
        }catch (Exception e){
            log.error("入住信息或志愿者信息保存出错"+e.getMessage());
            return CommonResult.failed();
        }
    }

    @ApiOperation("用户信息完善校验接口")
    @RequestMapping(value = "/verifyUserInfo", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult verifyUserInfo(Principal principal) {
        if(principal==null){
            return CommonResult.unauthorized(null);
        }
        UmsMember member = memberService.getCurrentMember();
        boolean verify = memberService.verifyUserInfo(member);
        if (isDebugEnabled) {
            log.debug("执行获取MbrMember数据集完善{}-->结果:{}",verify,member);
        }
        if(verify){
            return CommonResult.success(null, "用户信息完善");
        }
        return CommonResult.forbidden(null);
    }
}
